package com.shycloud.mido.music.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UpCompletionHandler;
import com.qiniu.storage.model.DefaultPutRet;
import com.shycloud.mido.music.domain.MisMusic;
import com.shycloud.mido.music.service.MisMusicService;
import com.shycloud.mido.music.util.CommonString;
import lombok.AllArgsConstructor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Xiaoxing Yu
 * @date 2020/8/12
 **/
@Component
@AllArgsConstructor
public class QiniuUploadCallbackHandler implements UpCompletionHandler {

	private static Log logger = LogFactory.getLog(QiniuUploadCallbackHandler.class);

	public final static String OSS_MUSIC_FILE = "http://music.file.joymido.com/";

	private RedisTemplate redisTemplate;

	/** 曲目 service */
	private MisMusicService misMusicService;

	@Override
	public void complete(String key, Response r) {
		//解析上传成功的结果
		DefaultPutRet putRet = null;
		try {
			putRet = new Gson().fromJson(r.bodyString(), DefaultPutRet.class);
//			String finalUrl = String.format("%s/%s", cdn, putRet.key);
		} catch (QiniuException e) {
			logger.info("QiniuException occured, ", e);
		}

//		Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
		Map<Object, Object> entries = (Map)redisTemplate.opsForValue().get(key);

		String updateBatchId = (String) entries.get("updateBatchId");
		MisMusic music = (MisMusic) entries.get("music");
		String ossMvFileName = (String) entries.get("ossMvFileName");

		logger.info("updateBatchId:" + updateBatchId);
		logger.info("music:" + JSONObject.toJSONString(music));
		logger.info("ossMvFileName:" + ossMvFileName);

		//更新redis上传缓存结果
		if (putRet.hash != null && putRet.hash.length() > 0) {
			redisTemplate.opsForValue().set(updateBatchId + ":" + music.getId(), 1, 1200, TimeUnit.SECONDS);
		} else {
			redisTemplate.opsForValue().set(updateBatchId + ":" + music.getId(), 0, 1200, TimeUnit.SECONDS);
		}

		//更新music的上传url
		music.setMvFile(OSS_MUSIC_FILE + ossMvFileName);
		//更新数据
		misMusicService.updateById(music);

		logger.info(key);
		logger.info(JSONObject.toJSONString(r));
	}

}
